package com.james.happyfarm.modules;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.james.happyfarm.PO.Animal;
import com.james.happyfarm.PO.Friend;
import com.james.happyfarm.PO.Ranch;
import com.james.happyfarm.network.KaiXinWap;

public class RanchModule {
	
	public final static String[] GUARD = {
		"\u7267\u573A\u5DE1\u67E5\u5458" //牧场巡查员
	};

	public List<Friend> getStealableFriend(String verifyCode) {
		List<Friend> friendList = new ArrayList<Friend>();
		friendList.add(new Friend(KaiXinWap.ME_UID, KaiXinWap.ME_USERNAME, ""));
		
		String url = KaiXinWap.KAIXINNETWORK_WAP + "/house/ranch/getfriendproduct2.php?verify=" + verifyCode;
		String resp = KaiXinWap.callURL(url);
		
		String regex = "<a href=\"/house/ranch/\\?[^>]*uid=([^;&]*)[^>]*>([^<]*)</a>[^\u53EF\u5077]*\u53EF\u5077";
		
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(resp);
		while(m.find()){
			friendList.add(new Friend(m.group(1), m.group(2), ""));
		}
		
		return friendList;
	}
	
	public Ranch getStealableAnimal(Ranch ranch, String verifyCode) {
		List<Animal> animalList = ranch.getAnimalList();
		
		String url =  KaiXinWap.KAIXINNETWORK_WAP + "/house/ranch/?verify=" + verifyCode + "&fuid=" + ranch.getOwner().getUid();
		String resp = KaiXinWap.callURL(url);
		
		resp = resp.replaceAll("\u5DF2\u5077\u8FC7", "\u0001"); //已偷过
		resp = resp.replaceAll("\u53EF\u5077", "\u0002"); //防偷期
		resp = resp.replaceAll("\u732A\u4ED4", "\u0003"); //猪仔
		resp = resp.replaceAll("\u6536\u83B7", "\u0004");//收获
		
		if (ranch.getOwner().getUid().equals(KaiXinWap.ME_UID)) {
			//收获
			String regex = "<a[^>]*href=\"/house/ranch/havest.php?[^>]*skey=([^&]*)&[^>]*type=(\\d*)[^>]*>";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(resp);
			while(m.find()) {
				animalList.add(new Animal(m.group(1), Integer.parseInt(m.group(2)), ranch));
			}
		} else {
			//偷		
			//check guard
			for (String guardStr : GUARD) {
				if (resp.indexOf(guardStr) != -1)
					return ranch;
			}
		
			String regex = "<a[^>]*href=\"/house/ranch/havest.php?[^>]*skey=([^&]*)&[^>]*type=(\\d*)[^>]*>";
		
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(resp);
			while(m.find()){
				animalList.add(new Animal(m.group(1), Integer.parseInt(m.group(2)), ranch));
			}
		}
		return ranch;
	}
	
	public String stealAnimal(Animal animal, String verifyCode) {		
		String url = KaiXinWap.KAIXINNETWORK_WAP + "/house/ranch/havest.php?skey=" + animal.getSkey() + "&type=" + animal.getType() + "&verify=" + verifyCode + "&fuid=" + animal.getOwner().getOwner().getUid();
		String resp = KaiXinWap.callURL(url);
		
		String regex = "<div class=\"tips1\">([^<]*)</div>";
		
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(resp);
		if(m.find()){
			return m.group(1);
		}
		
		return "no response!";		
	}
}
